package com.zy.ivideo.service;

import com.zy.ivideo.entity.CollectionEntity;
import com.zy.ivideo.entity.ResponseEntity;
import com.zy.ivideo.repository.CollectionRepository;
import com.zy.ivideo.repository.VideoMultitypeRepository;
import com.zy.ivideo.repository.VideoSimpleRepository;
import com.zy.ivideo.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;

@Service
public class CollectionService {
    @Autowired
    CollectionRepository repository;
    @Autowired
    EntityManager entityManager;

    @Autowired
    VideoSimpleRepository simpleRepository;

    @Autowired
    VideoMultitypeRepository multitypeRepository;

    /**
     * 收藏
     * @param entity
     * @return
     */
    public ResponseEntity<CollectionEntity> collection(CollectionEntity entity){
        CollectionEntity result = repository.save(entity);
        if (result!=null){
            int r=0;
            if (entity.getSourceflag()==0){
                r=simpleRepository.updateCollectionNum(1,entity.getItemcode());
            }else if (entity.getSourceflag()==1){
                r=multitypeRepository.updateCollectionNum(1,entity.getItemcode());
            }
            if (r>0){
                return ResponseUtils.success(result);
            }else{
                return ResponseUtils.failed("收藏失败");
            }

        }
        return ResponseUtils.failed("收藏失败");
    }


    /**
     * 取消收藏
     * @param entity
     * @return
     */
    public ResponseEntity<Boolean> unCollection(CollectionEntity entity){
        try{
            repository.deleteByItemcodeAndUserid(entity.getItemcode(),entity.getUserid());
            int r=0;
            if (entity.getSourceflag()==0){
                r=simpleRepository.updateCollectionNum(-1,entity.getItemcode());
            }else if (entity.getSourceflag()==1){
                r=multitypeRepository.updateCollectionNum(-1,entity.getItemcode());
            }
            if (r>0){
                return ResponseUtils.success(true);
            }else{
                return ResponseUtils.failed("取消收藏失败");
            }
        }
        catch (Exception ex){
            return ResponseUtils.failed("取消收藏失败，error:"+ex.getMessage());
        }

    }
}
